﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Data;

namespace M139.Api
{

    /// <summary>
    /// 类  名：JsonParser
    /// 描  述：JSON解析类
    /// </summary>
    public class JsonParser
    {
        #region 全局变量

        private JsonObject _json = new JsonObject();//寄存器
        private readonly string _SEMICOLON = "@semicolon";//分号转义符
        private readonly string _COMMA = "@comma"; //逗号转义符

        #endregion

        #region 字符串转义
        /// <summary>
        /// 字符串转义,将双引号内的:和,分别转成_SEMICOLON和_COMMA
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        private string StrEncode(string text)
        {
            MatchCollection matches = Regex.Matches(text, "\\\"[^\\\"]+\\\"");
            foreach (Match match in matches)
            {
                text = text.Replace(match.Value, match.Value.Replace(":", _SEMICOLON).Replace(",", _COMMA));
            }

            return text;
        }
        /// <summary>
        /// 字符串转义,将_SEMICOLON和_COMMA分别转成:和,
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        private string StrDecode(string text)
        {
            return text.Replace(_SEMICOLON, ":").Replace(_COMMA, ",");
        }

        #endregion

        #region JSON最小单元解析

        /// <summary>
        /// 最小对象转为JsonObject
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        private JsonObject DeserializeSingletonObject(string text)
        {
            JsonObject JsonObject = new JsonObject();

            MatchCollection matches = Regex.Matches(text, "(\\\"(?<key>[^\\\"]+)\\\":\\\"(?<value>[^,\\\"]+)\\\")|(\\\"(?<key>[^\\\"]+)\\\":(?<value>[^,\\\"\\}]+))");
            foreach (Match match in matches)
            {
                string value = match.Groups["value"].Value.Trim();
                JsonObject.Add(match.Groups["key"].Value, _json.ContainsKey(value) ? _json[value] : value);
            }

            return JsonObject;
        }

        /// <summary>
        /// 最小数组转为JsonArray
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        private JsonArray DeserializeSingletonArray(string text)
        {
            JsonArray JsonArray = new JsonArray();

            MatchCollection matches = Regex.Matches(text, "(\\\"(?<value>[^,\\\"]+)\")|(?<value>[^,\\[\\]]+)");
            foreach (Match match in matches)
            {
                string value = match.Groups["value"].Value;
                JsonArray.Add(_json.ContainsKey(value) ? _json[value] : StrDecode(value));
            }

            return JsonArray;
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        private string Deserialize(string text)
        {
            //text = StrEncode(text);//转义;和,

            int count = 0;
            string key = string.Empty;
            string pattern = "(\\{[^\\[\\]\\{\\}]+\\})|(\\[[^\\[\\]\\{\\}]+\\])";

            while (Regex.IsMatch(text, pattern))
            {
                MatchCollection matches = Regex.Matches(text, pattern);
                foreach (Match match in matches)
                {
                    key = "___key" + count + "___";

                    if (match.Value.Substring(0, 1) == "{")
                        _json.Add(key, DeserializeSingletonObject(match.Value));
                    else
                        _json.Add(key, DeserializeSingletonArray(match.Value));

                    text = text.Replace(match.Value, key);

                    count++;
                }
            }
            return text;
        }

        #endregion

        #region 公共接口

        /// <summary>
        /// 序列化JsonObject对象
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public JsonObject DeserializeObject(string text)
        {
            return _json[Deserialize(text)] as JsonObject;
        }

        /// <summary>
        /// 序列化JsonArray对象
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public JsonArray DeserializeArray(string text)
        {
            return _json[Deserialize(text)] as JsonArray;
        }

        #endregion
    }

    /// <summary>
    /// 类  名：JsonObject
    /// 描  述：JSON对象类
    /// </summary>
    public class JsonObject : Dictionary<string, object>
    { }

    /// <summary>
    /// 类  名：JsonArray
    /// 描  述：JSON数组类
    /// </summary>
    public class JsonArray : List<object>
    { }

}
